﻿namespace Anley.DomainDrivenDesign.Contract.Extension;

/// <summary>
/// 枚举扩展类
/// </summary>
public static class EnumExtension
{
    /// <summary>
    /// 获取枚举值描述
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public static string GetDescription(this Enum value)
    {
        var name = value.ToString();
        var field = value.GetType().GetField(name);
        if (field == null)
            return string.Empty;
        var attr = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute), false);
        if (attr == null)
            return field.Name;
        var desc = ((DescriptionAttribute)attr).Description;
        return desc ?? field.Name;
    }

    /// <summary>
    /// 字符串转枚举值
    /// </summary>
    /// <typeparam name="TEnum"></typeparam>
    /// <param name="value"></param>
    public static TEnum? TryParse<TEnum>(this string value)
        where TEnum : struct
    {
        if (string.IsNullOrWhiteSpace(value))
            return null;
        if (Enum.TryParse(value, true, out TEnum result) && Enum.IsDefined(typeof(TEnum), result))
            return result;
        return null;
    }

    /// <summary>
    /// 数值转枚举值
    /// </summary>
    /// <typeparam name="TEnum"></typeparam>
    /// <param name="value"></param>
    public static TEnum? TryParse<TEnum>(this int value)
        where TEnum : struct
    {
        return value.ToString().TryParse<TEnum>();
    }
}